import {createApp} from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import axios from 'axios';
import ant from 'ant-design-vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import App from './App.vue'
import router from './router'

import { usePermissStore } from './store/permiss'
import 'element-plus/dist/index.css'
import 'ant-design-vue/dist/antd.css'
import './assets/css/icon.css'


const app = createApp(App)

app.use(createPinia())

app.use(router)
app.use(ElementPlus, {
    locale: zhCn,
})
app.use(ant);
//app.mount('#app');
// 注册elementplus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
// 自定义权限指令
const permiss = usePermissStore()
app.directive('permiss', {
    mounted(el, binding) {
        if(!permiss.key.includes(String(binding.value))){
            el['hidden'] = true;
        }
    }
})

app.mount('#app')
// 全局配置 axios 的请求根路径
//axios.defaults.baseURL固定写法
axios.defaults.baseURL="http://139.196.160.103:8081";
axios.defaults.headers.get['Accept'] = 'application/json';
//axios.defaults.headers.post['Content-Type'] = 'application/json';

/**
 * vue3不支持以 Vue.prototype的方式绑定全局变量,只能以app.config.globalProperties.$http在全局绑定！
 * 将axios挂载为app的全局自定义属性后，每个组件可以通过this直接访问到全局挂载的自定义属性
 * e.g. this.$http.get('/login');
 * ===================================
 * 如果使用组合式API【setup()语法】，由于vue3.0没有this，需要使用getCurrentInstance来获取上下文
 * e.g.
 * const { proxy } = getCurrentInstance()
 proxy.$http.get('/api/getNewsList')
 .then((response)=>{
       console.log(response)
   });
 */
// 把 axios 挂载到 Vue.prototype 上，供每个 .vue 组件的实例直接使用
//$http可自己命名（建议使用$http）
app.config.globalProperties.$http = axios; // 关键语句
app.config.globalProperties.$axios = axios;
router.beforeEach((to, from, next) => {
    document.title = `${to.meta.title} | vue-manage-system`;
    const role = localStorage.getItem('ms_username');
    const permiss = usePermissStore();
    if (!role && to.path !== '/login') {
        next('/login');
    } else if (to.meta.permiss && !permiss.key.includes(to.meta.permiss)) {
        // 如果没有权限，则进入403
        next('/403');
    } else {
        next();
    }
});
